/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-05-25 17:31:22
 * @LastEditTime: 2024-08-24 08:52:11
 * @FilePath: /nest_study/server/src/modules/system/post/post.service.ts
 */
import { Injectable } from '@nestjs/common';
import { CreatePostDto, DeletePostrDto, QueryPostDto, UpdatePostDto } from './dto/index.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { SystemUserEntity } from '../user/entities/user.entity';
import { Repository } from 'typeorm';
import { SystemPostEntity } from './entities/post.entity';
import { ResultData } from 'src/common/utils/result';

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(SystemUserEntity)
    private readonly userRepo: Repository<SystemUserEntity>,
    @InjectRepository(SystemPostEntity)
    private readonly postRepo: Repository<SystemPostEntity>,
  ) { }

  
  async create(createPostDto: CreatePostDto) {
    let { name, code } = createPostDto;
    let entity = this.postRepo.createQueryBuilder('post');
    entity.where('post.name=:name OR post.code=:code', { name, code });
    let data = await entity.getOne();
    if (data) {
      return ResultData.fail(500, '职位已存在');
    }
    let res = await this.postRepo.save(createPostDto);
    return ResultData.ok(res);
  }

  async update(updateDto: UpdatePostDto) {
    try {
      let { id, name } = updateDto;
      if (!id) {
        return ResultData.fail(500, '参数缺失')
      }
      let result = await this.postRepo.findOne({
        where: { name }
      });
      if (result && result?.id != id) {
        return ResultData.fail(500, '职位名称已存在')
      }
      let data = await this.postRepo.findOne({
        where: { id }
      });
      if (!data) {
        return ResultData.fail(500, '更新信息不存在');
      }
      let res = await this.postRepo.update({ id }, updateDto);
      if (res.affected) {
        return ResultData.ok('更新成功');
      } else {
        return ResultData.fail(500, '更新失败')
      }
    } catch (err) {
      return ResultData.fail(500, '更新失败' + err)
    }
  }

  async delete(info: DeletePostrDto) {
    let { ids } = info;
    if (!ids || ids.length == 0) {
      return ResultData.fail(500, '参数错误')
    }
    let total = 0;
    for (let i = 0; i < ids.length; i++) {
      let id = ids[i];
      let entity = this.userRepo.createQueryBuilder('user');
      entity.where("JSON_CONTAINS(user.postIds,:postId)", { postId: id.toString() });
      const num = await entity.getCount();
      total += num;
    }
    if (total > 0) {
      return ResultData.fail(500, '职位正在被使用');
    }
    await this.postRepo.delete(ids);
    return ResultData.ok();
  }

  async findAll(query: QueryPostDto) {
    let entity = this.postRepo.createQueryBuilder('post');
    if (query.name) {
      entity.andWhere(`post.name LIKE "%${query.name}%"`);
    }
    entity.skip(query.size * (query.page - 1)).take(query.size);
    const [list, total] = await entity.getManyAndCount();
    return ResultData.ok({
      list,
      total,
      size: query.size,
      page: query.page
    })
  }
}
